import React, { Component } from "react";
import { StackActions, NavigationActions } from "react-navigation";
import SQLite from "react-native-sqlite-storage";
import {
  View,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
  Platform,
  ScrollView,
  Keyboard
} from "react-native";
import NavBarConfig from "../modules/NavBar";
import LoginStyles from "../../style/pages/login";
import TelSelect from "../modules/TelSelect";
import http from "../../util/http";
import { COUNTRY, LOGIN_API, SENDCODE_API } from "../../config/Api";
import { toast } from "../../util/tip";
import { getTimer } from "../../util/util";
import {
  loginSuccess,
  getLoginState,
  initDatabase
} from "../../util/loginStateManager";
import storage from "../../util/storage";
import { USER_ID } from "../../util/Const";
import JPushModule from "jpush-react-native";
import SplashScreen from "react-native-splash-screen";

// console.log(JPushModule)
class Login extends Component {
  static navigationOptions = ({ navigation }) =>
    NavBarConfig(
      {
        headerLeft: <View />,
        headerTitle: "登錄",
        headerRight: "",
        mode: "modal",
        header: null,
        headerMode: "none"
      },
      navigation
    );

  state = {
    username: "",
    password: "",
    code: "",
    verifyMsg: "獲取驗證碼",
    contryCode: "86",
    contries: [],
    isRequeting: false
  };

  componentDidMount() {
    // TODO:  正式环境去除
    // return;
    if (Platform.OS === "android") {
      JPushModule.initPush();
      JPushModule.notifyJSDidLoad(resultCode => {
        if (resultCode === 0) {
        }
      });
    } else {
      JPushModule.setupPush();
    }
  }

  handleSelect(country) {
    this.setState({
      contryCode: country.code
    });
  }

  async getCountrise() {
    const data = await http.get(COUNTRY);
    await this.setState({
      contries: data.data
    });
  }

  SplashScreenHide() {
    if (Platform.OS == "android") SplashScreen.hide();
  }

  async componentWillMount() {
    setTimeout(() => {
      this.SplashScreenHide();
    }, 1000);
    try {
      SQLite.openDatabase(
        { name: "my.db", location: "default" },
        async (db, obj) => {
          initDatabase(db);
          let flag = await getLoginState();
          if (flag) {
            this.loginSuccessHandle();
          }
        },
        () => {
          alert("error");
        }
      );
    } catch (e) {
      // alert(e.message);
    }

    this.getCountrise();
  }

  handleChangeUsername(text) {
    this.setState({
      username: text
    });
  }

  handleChangeCode(text) {
    this.setState({
      code: text
    });
    if(text.length === 6 ){
      Keyboard.dismiss();
    }
  }

  async handleLogin() {
    const tel = this.state.username.trim();
    const code = this.state.code.trim();
    if (!code) {
      toast("驗證碼不可為空");
      return;
    }

    const data = await http.post(LOGIN_API, {
      tel: this.state.contryCode + tel + "",
      code: code
    });
    // alert(JSON.stringify(data));

    if (data) {
      storage.set(USER_ID, data.data.uid + "");
      loginSuccess(data.data.token, this.state.contryCode + tel + "");
      this.loginSuccessHandle();
    }
  }

  loginSuccessHandle() {
    const resetAction = StackActions.reset({
      index: 0,
      actions: [NavigationActions.navigate({ routeName: "Home" })]
    });
    this.props.navigation.dispatch(resetAction);
  }

  async handleSendCode() {
    const value = this.state.username.trim();
    if (!value) {
      toast("手機號不能為空");
      return;
    }
    if (this.state.isRequeting) return;
    this.setState({
      isRequeting: true,
      verifyMsg: `发送中...`
    });
    const countryData = this.state.contries.find(
      item => item.code == this.state.contryCode
    );

    const data = await http.post(SENDCODE_API, {
      tel: this.state.contryCode + value,
      country: countryData.shortname
    });
    this.setState({
      isRequeting: false,
      verifyMsg: `獲取驗證碼`
    });

    if (data) {
      getTimer(
        50,
        time => {
          this.setState({
            verifyMsg: `${time}s`
          });
        },
        () => {
          this.setState({
            verifyMsg: "獲取驗證碼"
          });
        }
      );
    }
  }

  render() {
    const Container = Platform.OS == "ios" ? ScrollView : View;
    // const Container = View;
    return (
      <View style={LoginStyles.loginPage}>
        <Image
          style={LoginStyles.loginPageBg}
          source={require("../../assets/login/bg.jpg")}
        />
        <Container
          // keyboardDismissMode="interactive"
          keyboardShouldPersistTaps={true}
          style={{
            position: "absolute",
            zIndex: 999,
            top: 0,
            width: "100%",
            height: "100%"
          }}
        >
          <View style={LoginStyles.loginMainContent}>
            <View style={LoginStyles.logo}>
              <Image
                style={LoginStyles.logoImg}
                source={require("../../assets/80.png")}
              />
            </View>

            <View>
              <View style={LoginStyles.inputContainer}>
                <TelSelect
                  data={this.state.contries}
                  onSelect={this.handleSelect.bind(this)}
                />
                <TextInput
                  underlineColorAndroid="transparent"
                  placeholder="請輸入手機號"
                  keyboardType="phone-pad"
                  style={LoginStyles.inputItem}
                  onChangeText={this.handleChangeUsername.bind(this)}
                />
                <TouchableOpacity
                  style={[
                    LoginStyles.codeButton,
                    this.state.isRequeting ||
                    this.state.verifyMsg != "獲取驗證碼"
                      ? {
                          backgroundColor: "gray"
                        }
                      : {}
                  ]}
                  disabled={
                    this.state.isRequeting ||
                    this.state.verifyMsg != "獲取驗證碼"
                  }
                  onPress={this.handleSendCode.bind(this)}
                >
                  <Text style={[LoginStyles.codeText]}>
                    {this.state.verifyMsg}
                  </Text>
                </TouchableOpacity>
              </View>
              <View style={LoginStyles.inputContainer}>
                <View style={LoginStyles.leftItem}>
                  <Image source={require("../../assets/psw-icon.png")} />
                </View>
                <TextInput
                  underlineColorAndroid="transparent"
                  placeholder="請輸入短信驗證碼"
                  keyboardType="phone-pad"
                  style={LoginStyles.inputItem}
                  onChangeText={this.handleChangeCode.bind(this)}
                />
              </View>
            </View>

            <TouchableOpacity onPress={this.handleLogin.bind(this)}>
              <Text style={LoginStyles.loginButton}>登 錄</Text>
            </TouchableOpacity>
          </View>
        </Container>
      </View>
    );
  }
}

export default Login;
